package neatlogic.module.change.api;

import neatlogic.framework.asynchronization.threadlocal.UserContext;
import neatlogic.framework.auth.core.AuthAction;
import neatlogic.framework.change.constvalue.*;
import neatlogic.framework.change.dto.*;
import neatlogic.framework.common.constvalue.ApiParamType;
import neatlogic.framework.common.constvalue.GroupSearch;
import neatlogic.framework.crossover.CrossoverServiceFactory;
import neatlogic.framework.process.auth.PROCESS_BASE;
import neatlogic.framework.process.crossover.IProcessStepHandlerCrossoverUtil;
import neatlogic.framework.process.dto.ProcessTaskStepVo;
import neatlogic.framework.process.exception.process.ProcessStepUtilHandlerNotFoundException;
import neatlogic.framework.process.stephandler.core.IProcessStepInternalHandler;
import neatlogic.framework.process.stephandler.core.ProcessStepInternalHandlerFactory;
import neatlogic.framework.restful.annotation.Description;
import neatlogic.framework.restful.annotation.Input;
import neatlogic.framework.restful.annotation.OperationType;
import neatlogic.framework.restful.annotation.Param;
import neatlogic.framework.restful.constvalue.OperationTypeEnum;
import neatlogic.framework.restful.core.privateapi.PrivateApiComponentBase;
import neatlogic.module.change.dao.mapper.ChangeMapper;
import neatlogic.framework.change.exception.ChangeHandleHasNotStartedException;
import neatlogic.framework.change.exception.ChangeNoPermissionException;
import neatlogic.framework.change.exception.ChangeStepNotFoundException;
import neatlogic.module.change.service.ChangeService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@AuthAction(action = PROCESS_BASE.class)
@OperationType(type = OperationTypeEnum.OPERATE)
public class ChangeStepStartApi extends PrivateApiComponentBase {

    @Autowired
    private ChangeMapper changeMapper;

    @Autowired
    private ChangeService changeService;

    @Override
    public String getToken() {
        return "change/step/start";
    }

    @Override
    public String getName() {
        return "nmca.changestepstartapi.getname";
    }

    @Override
    public String getConfig() {
        return null;
    }

    @Input({
            @Param(name = "changeStepId", type = ApiParamType.LONG, isRequired = true, desc = "term.change.changestepid"),
            @Param(name = "source", type = ApiParamType.STRING, desc = "common.source")
    })
    @Description(desc = "nmca.changestepstartapi.getname")
    @Override
    public Object myDoService(JSONObject jsonObj) throws Exception {
        Long changeStepId = jsonObj.getLong("changeStepId");
        ChangeStepVo changeStep = changeMapper.getChangeStepById(changeStepId);
        if (changeMapper.checkChangeStepIsExists(changeStepId) == 0) {
            throw new ChangeStepNotFoundException(changeStepId);
        }
        /** 获取当前变更锁 **/
        changeMapper.getChangeLockById(changeStep.getChangeId());
        ChangeVo changeVo = changeMapper.getChangeById(changeStep.getChangeId());
//		changeService.getChangeStepDetail(changeStep);
        boolean workerIsTeam = false;
        /** 处理人或组 **/
        ChangeStepUserVo changeStepUserVo = changeMapper.getChangeStepUserByChangeStepId(changeStep.getId());
        if (changeStepUserVo != null && StringUtils.isNotBlank(changeStepUserVo.getUserVo().getUuid())) {
            changeStep.setWorker(GroupSearch.USER.getValuePlugin() + changeStepUserVo.getUserVo().getUuid());
        } else {
            ChangeStepTeamVo changeStepTeamVo = changeMapper.getChangeStepTeamByChangeStepId(changeStep.getId());
            if (changeStepTeamVo != null && StringUtils.isNotBlank(changeStepTeamVo.getTeamUuid())) {
                workerIsTeam = true;
                changeStep.setWorker(GroupSearch.TEAM.getValuePlugin() + changeStepTeamVo.getTeamUuid());
            }
        }
        if (!changeService.isStartableChangeStep(changeVo, changeStep)) {
            throw new ChangeNoPermissionException(ChangeOperationType.STARTCHANGESTEP.getText());
        }

        /** 开始变更步骤时，将变更步骤状态设置为“处理中” **/
        changeStep.setId(changeStepId);
        changeStep.setStatus(ChangeStatus.RUNNING.getValue());
        changeMapper.updateChangeStepStatus(changeStep);

        /** 如果变更步骤开始之前是指定到处理组，当前用户点击开始之后，将处理组删掉，设置当前用户为处理人 **/
        if (workerIsTeam) {
            changeMapper.deleteChangeStepTeamByChangeStepId(changeStepId);
            changeMapper.insertChangeStepUser(new ChangeStepUserVo(changeStep.getChangeId(), changeStepId, UserContext.get().getUserUuid(true)));
        }

        /** 开始变更步骤时，触发更新processtask_step_worker和processtask_step_user数据 **/
        ProcessTaskStepChangeVo processTaskStepChangeVo = changeMapper.getProcessTaskStepChangeHandleByChangeId(changeStep.getChangeId());
        if (processTaskStepChangeVo == null) {
            throw new ChangeHandleHasNotStartedException();
        }
        IProcessStepInternalHandler processStepUtilHandler = ProcessStepInternalHandlerFactory.getHandler(ChangeProcessStepHandlerType.CHANGEHANDLE.getHandler());
        if (processStepUtilHandler == null) {
            throw new ProcessStepUtilHandlerNotFoundException(ChangeProcessStepHandlerType.CHANGEHANDLE.getHandler());
        }
        processStepUtilHandler.updateProcessTaskStepUserAndWorker(processTaskStepChangeVo.getProcessTaskId(), processTaskStepChangeVo.getProcessTaskStepId());

        /** 生成活动 **/
        ProcessTaskStepVo currentProcessTaskStepVo = new ProcessTaskStepVo();
        currentProcessTaskStepVo.setProcessTaskId(processTaskStepChangeVo.getProcessTaskId());
        currentProcessTaskStepVo.setId(processTaskStepChangeVo.getProcessTaskStepId());
        currentProcessTaskStepVo.getParamObj().put("changeStepName", changeStep.getName());
        currentProcessTaskStepVo.getParamObj().putAll(jsonObj);
        IProcessStepHandlerCrossoverUtil processStepHandlerCrossoverUtil = CrossoverServiceFactory.getApi(IProcessStepHandlerCrossoverUtil.class);
        processStepHandlerCrossoverUtil.audit(currentProcessTaskStepVo, ChangeAuditType.STARTCHANGESTEP);
        processStepHandlerCrossoverUtil.notify(currentProcessTaskStepVo, ChangeTriggerType.STARTCHANGESTEP);
        processStepHandlerCrossoverUtil.action(currentProcessTaskStepVo, ChangeTriggerType.STARTCHANGESTEP);
        return null;
    }

}
